package com.example.shiro_springboot.realm;

import com.example.shiro_springboot.entity.User;
import com.example.shiro_springboot.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    // 自定义授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("开始授权");
        // 登录名
        String uname = principalCollection.getPrimaryPrincipal().toString();
        // 查询当前用户的权限  -- 从数据库获取
        List<String> list = userService.selPermissionInfoByUname(uname);
        // 将当前用户的权限赋给shiro
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(list);
//        // 还可以查询角色信息 -- 从数据库
//        authorizationInfo.addRoles(roles);

        return authorizationInfo;
    }

    // 自定义登录认证逻辑，当shiro的login方法被执行时，底层自动调用此方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("开始登录认证");
        // 用户名
        String uname = token.getPrincipal().toString();
        // 获取用户信息
        User user = userService.getUserInfoByUname(uname);
        if (user != null) {
            // 校验密码
            AuthenticationInfo info = new SimpleAuthenticationInfo(uname, user.getPwd(), ByteSource.Util.bytes("zhangjq"), getName());
            return info;
        }

        return null;
    }
}
